# -*- coding: utf-8 -*-
# filename: tcp_server.py

import sys
import socket

ACTION_NONE = 0x00
ACTION_PUSH_X = 0x01
ACTION_PUSH_Y = 0x02
ACTION_ROTATE_CW = 0x03
ACTION_ROTATE_ACW = 0x04
ACTION_TURN_XP = 0x05
ACTION_TURN_XN = 0x06
ACTION_TURN_YP = 0x07
ACTION_TURN_YN = 0x08

Tips = {
    ACTION_NONE: 'NO-OPS',
    ACTION_PUSH_X: '↑↓ X PUSH',
    ACTION_PUSH_Y: '←→ Y PUSH',
    ACTION_ROTATE_CW: 'CLOCKWISE ROTATE',
    ACTION_ROTATE_ACW: 'ANTICLOCKWISE ROTATE',
    ACTION_TURN_XP: '↑ FRONT 90°',
    ACTION_TURN_XN: '↓ BACK 90°',
    ACTION_TURN_YP: '← LEFT 90°',
    ACTION_TURN_YN: '→ RIGHT 90°',
}


def writeAction(data):
    with open("action.data", "wb") as fs:
        fs.write(data)


def tcp_server(port='8080'):
    tcp_addr = ('0.0.0.0', int(port))
    tcps = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # tcps.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
    tcps.bind(tcp_addr)
    tcps.listen(1)
    client, addr = tcps.accept()

    while True:
        try:
            tcp_data = client.recv(1)
            if len(tcp_data) == 0:
                client.close()
                client, addr = tcps.accept()
                tcp_data = client.recv(1)
            else:
                print map(ord, tcp_data)
                if tcp_data[0] == chr(ACTION_NONE):
                    writeAction(Tips[ACTION_NONE])
                elif tcp_data[0] == chr(ACTION_PUSH_X):
                    writeAction(Tips[ACTION_PUSH_X])
                elif tcp_data[0] == chr(ACTION_PUSH_Y):
                    writeAction(Tips[ACTION_PUSH_Y])
                elif tcp_data[0] == chr(ACTION_ROTATE_CW):
                    writeAction(Tips[ACTION_ROTATE_CW])
                elif tcp_data[0] == chr(ACTION_ROTATE_ACW):
                    writeAction(Tips[ACTION_ROTATE_ACW])
                elif tcp_data[0] == chr(ACTION_TURN_XP):
                    writeAction(Tips[ACTION_TURN_XP])
                elif tcp_data[0] == chr(ACTION_TURN_XN):
                    writeAction(Tips[ACTION_TURN_XN])
                elif tcp_data[0] == chr(ACTION_TURN_YP):
                    writeAction(Tips[ACTION_TURN_YP])
                elif tcp_data[0] == chr(ACTION_TURN_YN):
                    writeAction(Tips[ACTION_TURN_YN])
                # tcp_data = None
        except Exception as e:
            print e
            client.close()
            client, addr = tcps.accept()


if __name__ == '__main__':
    if len(sys.argv) == 2:
        print sys.argv[1]
        tcp_server(sys.argv[1])
    else:
        tcp_server()
